//
//  userAccount.swift
//  XJWeiBo
//
//  Created by 徐健 on 16/3/12.
//  Copyright © 2016年 徐健. All rights reserved.
//

import UIKit
import AFNetworking

let userInfoKey = "cn.itcast.account"

class userAccount: NSObject {
    //单例对象
    static let onlyUserAccount = userAccount()

    
    
    
    
    
    //计算型属性
    var userLogin:Bool{
        return access_token != nil
    }
    
    
    override private init() {
        super.init()
        self.getUserInfo()
    }
    
    

    var access_token:String?
    
    var expires_in:NSTimeInterval = 0{
        
        didSet{
            espires_data = NSDate(timeIntervalSinceNow: expires_in)
        }
        
    }
    //过期日期
    var espires_data:NSDate?
    
    var uid:String?
    
    var name:String?
    
    var avatar_large:String?{
        didSet{
            headImageURL = NSURL(string: avatar_large ?? "")
        }
    }
    
    
    
    var headImageURL:NSURL?
    
    
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) { }
    
    override var description:String{
        
        // 只读属性
        let keys = ["access_token","expires_in","uid","name","avatar_large","espires_data"]
        
        let accountDic = self.dictionaryWithValuesForKeys(keys)
        
        return accountDic.description
    
    }
    
}


extension userAccount {
    func saveUserInfo(dict:[String:AnyObject]){
        self.setValuesForKeysWithDictionary(dict)
        
        //保存当前对象所有属性
        let u = NSUserDefaults.standardUserDefaults()
        
        let keys = ["access_token","expires_in","uid","name","avatar_large"]
        
        let accountDic = self.dictionaryWithValuesForKeys(keys)
        
        u.setObject(accountDic, forKey: userInfoKey)
        
        
        //立即同步
        u.synchronize()
        
    }
    
    
    func getUserInfo(){
        guard let dic = NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey) as? [String : AnyObject] else{
            return
        }
        
        self.setValuesForKeysWithDictionary(dic)
        
        
        if self.espires_data?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            print("正常使用")
        }else{
            print("已经过期")
            self.access_token = nil
        }
        
    }
    
}

extension userAccount{
    func loadAccessToken(code:String,finished:(isSuccess:Bool)->()){
        
        let AFN = AFHTTPSessionManager()
        
        //支持此格式
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        
        AFN.POST(urlString, parameters:parameters,progress: nil,success: { (_, result) -> Void in
            
            //获取token
            guard let dict = result as? [String:NSObject] else{
                
                
                
                //失败执行闭包
                finished(isSuccess: false)
                
                
                
                
                return
            }
            
            
            self.loadUserInfo(dict, finished: finished)
            
            //            let token = dict["access_token"]
            
            
            //            print(token)
            
            
            }) { (_, error) -> Void in
                
                
                
                
                //失败执行闭包
                finished(isSuccess: false)

                
                
                
                print(error)
        }
        
    }
    
    private func loadUserInfo(dict : [String : AnyObject],finished:(isSuccess:Bool)->()){
        let token = dict["access_token"] as! String
        
        let AFN = AFHTTPSessionManager()
        
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        
        let uid = dict["uid"] as! String
        
        let parameters = ["access_token":token,"uid":uid]
        
        
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            guard var userInfoDic = result as? [String:AnyObject] else{

                //失败回调
                finished(isSuccess: false)
                
                
                return
            }
            
            
            //合并字典
            for (k,v) in dict{
                userInfoDic[k] = v
            }
            
            
            //            //保存到沙盒
            //            NSUserDefaults.standardUserDefaults().setObject(userInfoDic, forKey: "cn.itcast.account")
            
            userAccount.onlyUserAccount.saveUserInfo(userInfoDic)
            
            
            
            //成功回调
            finished(isSuccess: true)
            
            
            }) { (_, error) -> Void in
                
                
                
                //失败回调
                finished(isSuccess: false)
                
                
                
                print(error)
        }
    }

    
}

